package com.youlai.boot.modules.game.service;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class OssService {

    @Value("${oss.aliyun.endpoint}")
    private String endpoint;

    @Value("${oss.aliyun.access-key-id}")
    private String accessKeyId;

    @Value("${oss.aliyun.access-key-secret}")
    private String accessKeySecret;

    @Value("${oss.aliyun.bucket-name}")
    private String bucketName;

    public String uploadFileAvatar(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            log.error("上传文件为空");
            return null;
        }

        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            originalFilename = "unknown_file";
        }

        OSS ossClient = null;
        try {
            // 创建OSS实例
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            
            // 检查OSS客户端是否成功创建
            if (ossClient == null) {
                log.error("OSS客户端创建失败");
                return null;
            }

            // 获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            
            // 生成唯一文件名 (UUID + 原始文件名)
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = uuid + originalFilename;

            // 按日期分类存储: 2022/10/11/xxxxx.jpg
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + fileName;

            log.info("正在上传文件到OSS: bucket={}, fileName={}", bucketName, fileName);
            
            // 上传文件到OSS
            ossClient.putObject(bucketName, fileName, inputStream);

            // 拼接并返回文件URL (确保去掉空格)
            String fileUrl = ("https://" + bucketName + "." + endpoint + "/" + fileName).trim();
            log.info("文件上传成功，URL: {}", fileUrl);
            return fileUrl;
        } catch (IOException e) {
            log.error("文件上传IO异常", e);
            return null;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return null;
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public boolean deleteFile(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            log.error("删除文件路径为空");
            return false;
        }

        OSS ossClient = null;
        try {
            // 创建OSS客户端
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            
            // 从URL中提取对象名称
            String objectName = filePath.substring(filePath.indexOf(bucketName + "." + endpoint + "/") + 
                                                (bucketName + "." + endpoint + "/").length());
            
            log.info("正在删除OSS文件: bucket={}, objectName={}", bucketName, objectName);
            
            // 删除文件
            ossClient.deleteObject(bucketName, objectName);
            log.info("成功删除文件: {}", objectName);
            return true;
        } catch (Exception e) {
            log.error("删除文件失败: {}", filePath, e);
            return false;
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
